//
//  EXPredicate.m
//  ORM
//
//  Created by PH on 29.12.09.
//  Copyright 2009-2010 Codesign. All rights reserved.
//

#import "EXPredicate.h"
#import "EXObjectStore.h"

@implementation EXPredicate

@synthesize filterBlock;

- (id)initWithClass:(Class)_cls objectStore:(EXObjectStore*)_objectStore {
	if ((self = [super init])) {
		cls = _cls;
		condBlocks = [[NSMutableArray alloc] init];
		objectStore = _objectStore;
	}
	return self;
}

+ (EXPredicate*)predicateWithClass:(Class)_cls objectStore:(EXObjectStore*)_objectStore {
	return [[[self alloc] initWithClass: _cls objectStore: _objectStore] autorelease];
}

- (EXPredicate*)restrictField:(NSString*)fieldName equalsString:(NSString*)value {
	[condBlocks addObject: [[objectStore KVStore] stringEqualConditionWithColumnName: [NSString stringWithFormat: @"field_%@", fieldName]
																			   value: value]];
	return self;
}

- (EXPredicate*)restrictField:(NSString*)fieldName equalsObject:(NSObject<EXMappableObject>*)value {
	NSString* sValue = [objectStore IDOfObject: value];
	return [self restrictField: fieldName equalsString: sValue];
}

- (EXPredicate*)restrictField:(NSString*)fieldName containsString:(NSString*)value {
	[condBlocks addObject: [[objectStore KVStore] stringIncludedConditionWithColumnName: [NSString stringWithFormat: @"field_%@", fieldName]
																				  value: value]];
	return self;
}

- (EXPredicate*)restrictField:(NSString*)fieldName lessThanNumber:(double)value {
	[condBlocks addObject: [[objectStore KVStore] numberLessThanConditionWithColumnName: [NSString stringWithFormat: @"field_%@", fieldName]
																				  value: value]];
	return self;
}

- (EXPredicate*)restrictField:(NSString*)fieldName greaterThanNumber:(double)value {
	[condBlocks addObject: [[objectStore KVStore] numberGreaterThanConditionWithColumnName: [NSString stringWithFormat: @"field_%@", fieldName]
																				  value: value]];
	return self;
}

- (EXPredicate*)restrictField:(NSString*)fieldName equalsNumber:(double)value {
	[condBlocks addObject: [[objectStore KVStore] numberEqualConditionWithColumnName: [NSString stringWithFormat: @"field_%@", fieldName]
																				  value: value]];
	return self;
}

- (void(^)(void*))condBlock {
	return [[^void(void* db) {
		for (void(^condBlock)(void*) in condBlocks) {
			condBlock(db);
		}
	} copy] autorelease];
}

- (Class)predicateClass {
	return cls;
}

- (void)dealloc {
	[condBlocks release];
	[filterBlock release];
	[super dealloc];
}

@end
